/**
 * 递归判断对象或数组是否为空
 * @param value 要检查的值
 * @returns boolean
 */
export const isDeepEmpty: (value: any) => boolean = (value: any) => {
  // 检查基本数据类型
  if (value === null || value === undefined) return true; // null 和 undefined
  if (typeof value === 'boolean') return false; // 布尔值不为空
  if (typeof value === 'number') return false; // 0 被视为非空
  if (typeof value === 'string') return value.trim() === ''; // 空字符串

  // 递归检查对象和数组
  if (Array.isArray(value)) {
    return value.every(isDeepEmpty);
  }
  if (typeof value === 'object') {
    return (
      Object.keys(value).length === 0 || Object.values(value).every(isDeepEmpty)
    );
  }

  return false;
};


export function calculateNumber<T extends 'string' | 'number'>(
  operator: string,
  numbers: any[],
  decimalPlaces = 2,
  returnType: T = 'string' as T,
): T extends 'string' ? string : number {
  // 将所有输入的数字转换为 BigNumber
  let result = new BigNumber(numbers[0] || 0);
  // 根据操作符执行相应的操作
  for (let i = 1; i < numbers.length; i++) {
    let currentNumber = new BigNumber(numbers[i] || 0);

    switch (operator) {
      case '+':
        result = result.plus(currentNumber);
        break;
      case '-':
        result = result.minus(currentNumber);
        break;
      case '*':
        result = result.times(currentNumber);
        break;
      case '/':
        // 确保不会除以零
        if (currentNumber.isZero()) {
          throw new Error('Division by zero is not allowed');
        }
        result = result.div(currentNumber);
        break;
      default:
        throw new Error(`Unsupported operator: ${operator}`);
    }
  }


export function safeParse(jsonString, defaultValue = null) {
  try {
    return JSON.parse(jsonString);
  } catch (error) {
    console.error('JSON.parse error:', error);
    return defaultValue;
  }
}

export function safeStringify(value, defaultValue = '{}') {
  try {
    return JSON.stringify(value);
  } catch (error) {
    console.error('JSON.stringify error:', error);
    return defaultValue;
  }
}

/**
 * 去除对象里的空属性
 * @param obj
 * @param trim 是否默认去除空格
 * @returns
 */
export const removeEmptyFields = (obj: { [key: string]: any }, trim = true) => {
  // 如果是空对象，直接返回空对象
  if (Object.keys(obj).length === 0) {
    return {};
  }
  return Object.keys(obj).reduce((acc: { [key: string]: any }, key: string) => {
    let value = obj[key];
    if (
      value !== null &&
      value !== undefined &&
      value !== '' &&
      !(Array.isArray(value) && value.length === 0) && // 空数组
      !(typeof value === 'object' && Object.keys(value).length === 0) // 空对象
    ) {
      acc[key] = trim
        ? typeof value === 'string'
          ? value.trim()
          : value
        : value;
    }
    return acc;
  }, {});
};

export const aLink=(res)=>{
    const a = document.createElement('a');
    a.href = res?.url;
    a.download = res?.url;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}